import sys, string
from mokocard.util.exceptionutil import printStack
from mokocard.util.logutil import LogUtil

def listFile(myFile):

    try:
        LogUtil.writeLog("try to load file " + myFile)
        # load shortcut file
        f = open(myFile, 'r')
        myrows = f.readlines()
        
        # close file
        f.close()

        return myrows
        
    except IOError, (errno, strerror):
        LogUtil.writeLog("Impossibile to open file " + myFile)
        return None

def importFile(myFile, separator):

        myrows = listFile(myFile)
        
        if myrows == None:
            return None
                
        newCards = []
        
        count = 0
        # parsing rows
        for row in myrows:
            try:
                # replace end of line with no char
                row = row.replace("\n", "")
                #print row
                tmpTokens = row.split(separator)
                #print tmpTokens
                if tmpTokens[0] != None and tmpTokens[1] != None:
                    # insert data in database
                    newCards.append(tmpTokens)
                    count = count + 1
                    
            except:
                printStack(sys.exc_info())
                LogUtil.writeLog("impossible to insert row: '" + row + "'")
                return None

        #LogUtil.writeLog(newCards)
        return newCards
    
def listConfigFile(myConfigFile):

    try:
        LogUtil.writeLog("try to load file " + myConfigFile)
        # load shortcut file
        f = open(myConfigFile, 'r')
        myrows = f.readlines()
        #print len(myrows)
        
        # close file
        f.close()
        
        return myrows
        
    except IOError, (errno, strerror):
        LogUtil.writeLog(strerror)
        
def manageConfigFile(myConfigFile):

        myrows = listConfigFile(myConfigFile)
        
        # this is a dictionary
        hashConfig = {}
        
        # parsing rows
        for row in myrows:
            if row[0] == "#":
                # it's a comment
                continue
            try:
                tmpTokens = row.split('=')
                if tmpTokens[0] != None and tmpTokens[1] != None:
                    # replace end of line
                    hashConfig[tmpTokens[0]] = string.replace(tmpTokens[1],'\n','')
            except:
                LogUtil.writeLog(printStack(sys.exc_info()))
    
        LogUtil.writeLog(hashConfig)
        return hashConfig